package com.ruoyi.framework.config;

import com.ruoyi.framework.utils.StringUtils;
import com.ruoyi.framework.xss.XssFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.DispatcherType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Filter配置
 *
 * @author ruoyi
 */
@Configuration
@ConditionalOnProperty(value = "ruoyi.xss.enabled", havingValue = "true")
public class FilterConfig {
    @Value("${ruoyi.xss.url-excludes:}")
    private String excludes;

    @Value("${ruoyi.xss.url-patterns:}")
    private String urlPatterns;

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Bean
    public FilterRegistrationBean xssFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new XssFilter());
        // 若依自带的
        List<String> ruoyiUrlPatternsList = Arrays.asList("/system/*,/monitor/*,/tool/*".split(","));
        List<String> urlPatternsList = new ArrayList<>(ruoyiUrlPatternsList);
        if (StringUtils.isNotEmpty(urlPatterns.trim())) {
            urlPatternsList.addAll(Arrays.asList(urlPatterns.split(",")));
        }
        String[] urlPatternsArray = new String[urlPatternsList.size()];
        urlPatternsList.toArray(urlPatternsArray);
        registration.addUrlPatterns(urlPatternsArray);

        registration.setName("xssFilter");
        registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
        Map<String, String> initParameters = new HashMap<String, String>();
        // 若依自带的
        StringBuilder excludesBuilder = new StringBuilder("/system/notice/*");
        if (StringUtils.isNotEmpty(excludes.trim())) {
            excludesBuilder.append(",").append(excludes.trim());
        }
        initParameters.put("excludes", excludesBuilder.toString());
        registration.setInitParameters(initParameters);
        return registration;
    }
}
